package ftp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;


import sun.net.ftp.FtpClient;

public class SFtpClient {
	private FTPSClient sftpClient;
	private String server;
	private String user;
	private String password;
	private String path;
	
	
	public SFtpClient(String server, String user, String password) {
		this.server = server;
		this.user = user;
		this.password = password;
	}
	
	public SFtpClient(String server, String user, String password, String path) {
		this.server = server;
		this.user = user;
		this.password = password;
		this.path = path;
	}

	public void upload(String text, String fileName, String path) throws Exception {
		this.path = path;
		connectServer();
		uploadText(text, fileName);
	}
	
	public void upload(String text, String fileName) throws Exception {
		connectServer();
		uploadText(text, fileName);
	}
	
	private void connectServer() throws IOException {
		sftpClient = new FTPSClient("FSTP");
		sftpClient.connect(server);
		sftpClient.login(user, password);
		if (path.length() != 0)
			sftpClient.mlistDir(path);
		sftpClient.setFileType(FTP.BINARY_FILE_TYPE);

	}

	private void uploadText(String text, String fileName) throws Exception {
		OutputStream os = null;
		BufferedReader br = null;
		try {
			os = sftpClient.storeFileStream(fileName);
			
			br = new BufferedReader(
					new StringReader(text));
			String line = null;
			while ((line = br.readLine()) != null) {
				os.write(line.getBytes());
			}
		} finally {
			if (br != null) {
				br.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		String server = "172.20.230.5";
		String user = "yellowbook";
		String password = "ybpass";
		String path = "/home/yellowbook";
		SFtpClient ftp = new SFtpClient(server, user, password, path);
		ftp.upload("test ftp", "wood_test");
	}

}
